package com.fessc.develop.utils;

import com.fessc.develop.entity.ApplicationPropertiesVo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Component
public class OkHttpUtil {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");
    private static final MediaType TEXT = MediaType.parse("application/text; charset=utf-8");

    @Resource
    private OkHttpClient okHttpClient;

    @Resource
    private VirtualJsonUtil virtualJsonUtil;

    @Resource
    private ApplicationPropertiesVo applicationPropertiesVo;

    /**
     * get 请求
     *
     * @param url 请求url地址
     * @return string
     */
    public String doGet(String url) {
        return doGet(url, null, null);
    }


    /**
     * get 请求
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public String doGet(String url, Map<String, String> params) {
        return doGet(url, params, null);
    }

    /**
     * get 请求
     *
     * @param url     请求url地址
     * @param headers 请求头字段 {k1, v1 k2, v2, ...}
     * @return string
     */
    public String doGet(String url, String[] headers) {
        return doGet(url, null, headers);
    }


    /**
     * get 请求
     *
     * @param url     请求url地址
     * @param params  请求参数 map
     * @param headers 请求头字段 {k1, v1 k2, v2, ...}
     * @return string
     */
    public String doGet(String url, Map<String, String> params, String[] headers) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            boolean firstFlag = true;
            for (String key : params.keySet()) {
                if (firstFlag) {
                    sb.append("?").append(key).append("=").append(params.get(key));
                    firstFlag = false;
                } else {
                    sb.append("&").append(key).append("=").append(params.get(key));
                }
            }
        }

        Request.Builder builder = new Request.Builder();
        if (headers != null && headers.length > 0) {
            if (headers.length % 2 == 0) {
                for (int i = 0; i < headers.length; i = i + 2) {
                    builder.addHeader(headers[i], headers[i + 1]);
                }
            } else {
                log.warn("headers's length[{}] is error.", headers.length);
            }
        }

        Request request = builder.url(sb.toString()).build();
        log.info("请求报文地址：{}", url);
        return execute(request);
    }

    /**
     * post 请求
     *
     * @param url   请求url地址
     * @param param 请求参数
     * @return string
     */
    public String doPost(String url, String param) {
        log.info("请求报文地址：{}", url);
        return executePost(url, param, JSON, null);
    }


    /**
     * post 请求, 请求数据为 json 的字符串
     *
     * @param url  请求url地址
     * @param json 请求数据, json 字符串
     * @return string
     */
    public String doPostJson(String url, String json) {
        log.info("请求报文地址：{}", url);
        return executePost(url, json, JSON);
    }

    /**
     * post 请求, 请求数据为 json 的字符串
     *
     * @param url  请求url地址
     * @param json 请求数据, json 字符串
     * @param headers 请求头字段
     * @return string
     */
    public String doPostJson(String url, String json, Map<String, String> headers) {
        log.info("请求报文地址：{}", url);
        return executePost(url, json, JSON, headers);
    }

    /**
     * post 请求, 请求数据为 xml 的字符串
     *
     * @param url 请求url地址
     * @param xml 请求数据, xml 字符串
     * @return string
     */
    public String doPostXml(String url, String xml) {
        log.info("请求报文地址：{}", url);
        return executePost(url, xml, XML);
    }

    private String executePost(String url, String data, MediaType contentType) {

        //log.info("模拟报文启用：" + applicationPropertiesVo.getAppLocalJsonFlag());
        if (BusiUtil.isEquals("true", applicationPropertiesVo.getAppLocalJsonFlag())) {
            String res = virtualJsonUtil.readLocalFile(applicationPropertiesVo.getAppLocalJsonPath(), data);
            if (BusiUtil.isNotNull(res) && !"null".equalsIgnoreCase(res)) {
                log.info("返回模拟报文：" + res);
                return res;
            }
        }

        RequestBody requestBody = RequestBody.create(contentType, data);
        /*
        Headers.Builder headersBulider = new Headers.Builder();
        headersBulider.add("Content-Type", "application/json");
        String Unique_Seq_No = UUID.randomUUID().toString();
        log.info("header流水号：" + Unique_Seq_No);
        headersBulider.add("uniqueSeqNo", Unique_Seq_No);
        Request request = new Request.Builder().url(url).headers(headersBulider.build()).post(requestBody).build();
        */
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return execute(request);
    }

    private String executePost(String url, String data, MediaType contentType, Map<String, String> headers) {

        //log.info("模拟报文启用：" + applicationPropertiesVo.getAppLocalJsonFlag());
        if (BusiUtil.isEquals("true", applicationPropertiesVo.getAppLocalJsonFlag())) {
            String res = virtualJsonUtil.readLocalFile(applicationPropertiesVo.getAppLocalJsonPath(), data);
            if (BusiUtil.isNotNull(res) && !"null".equalsIgnoreCase(res)) {
                log.info("返回模拟报文：" + res);
                return res;
            }
        }
        RequestBody requestBody = RequestBody.create(contentType, data);
        Request.Builder builder = new Request.Builder();
        if (BusiUtil.isNotNull(headers)) {
            for (String key : headers.keySet()) {
                builder.addHeader(key, headers.get(key));
            }
        }
        Request request = builder.url(url).post(requestBody).build();

        return execute(request);
    }

    private String execute(Request request) {
        Response response = null;
        try {
            okHttpClient.newBuilder()
                    .connectTimeout(30L, TimeUnit.SECONDS)  // 连接超时30秒
                    .readTimeout(30L, TimeUnit.SECONDS)     // 读取超时30秒
                    .writeTimeout(30L, TimeUnit.SECONDS);   // 写入超时30秒
            String beginTime = DateUtil.getCurrentDateTime(DateUtil.DATE_TIME_MS_FORMAT);
            log.info("报文发送时间：" + beginTime);
            response = okHttpClient.newCall(request).execute();
            String endTime = DateUtil.getCurrentDateTime(DateUtil.DATE_TIME_MS_FORMAT);
            log.info("报文返回时间：" + endTime);
            if (response.isSuccessful()) {
                String res = response.body().string();
                log.info("请求返回报文：" + res);
                return res;
            } else {
                log.info("请求失败，状态码：" + response.code());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("请求报文异常：" + e.getMessage());
            throw ExceptionUtil.businessException("EE4009");
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                log.error("关闭Response异常：" + e.getMessage());
            }
        }
        return "";
    }

    public Map<String, String> getRequestHeaders(String appkey, String url, String bankId) {
        Map<String, String> requestHeaders = new HashMap<>();
        if (BusiUtil.isNotNull(appkey)) {
            requestHeaders.put("APP_Key", appkey);
        }
        if (BusiUtil.isNotNull(url)) {
            requestHeaders.put("URI", url);
        }
        requestHeaders.put("Content-Type", "application/json");
        requestHeaders.put("Unique_Seq_No", BusiUtil.getSerialNumber(bankId, "", 5));
        requestHeaders.put("requestTime", DateUtil.getCurrentDateTime("yyyyMMddHHmmss"));
        return requestHeaders;
    }

}
